Golang : Check if os.Stdin input data is piped or from terminal
There are times we need to write a program that need to behave in one way according to input from pipe and in another way according to input from terminal ( such as keyboard).
In this tutorial, we will learn how to determine the type of inputs... if it is pipe data or from terminal. The codes below will use data from os.Stdin.Stat()
function to determine if the incoming data from terminal or pipe.
package main
import (
"fmt"
"io/ioutil"
"os"
"bufio"
)
func main() {
fi, _ := os.Stdin.Stat() // get the FileInfo struct describing the standard input.
if (fi.Mode() & os.ModeCharDevice) == 0 {
fmt.Println("data is from pipe")
// do things for data from pipe
bytes, _ := ioutil.ReadAll(os.Stdin)
str := string(bytes)
fmt.Println(str)
} else {
fmt.Println("data is from terminal")
// do things from data from terminal
ConsoleReader := bufio.NewReader(os.Stdin)
fmt.Println("Enter your name : ")
input, err := ConsoleReader.ReadString('\n')
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println("Your name is : ",input)
}
}
Sample output :
>echo "good morning" | ./checkinput
data is from pipe
good morning
> ./checkinput
data is from terminal
Enter your name :
Boo
Your name is : Boo
Reference :
See also : Golang : Read input from console line
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+9.6k Golang : Sort and reverse sort a slice of floats
+4k Detect if Google Analytics and Developer Media are loaded properly or not
+8.3k Golang : Auto-generate reply email with text/template package
+7.4k Golang : Accessing dataframe-go element by row, column and name example
+23.1k Golang : Randomly pick an item from a slice/array example
+25.2k Golang : Storing cookies in http.CookieJar example
+8.8k Golang : Gorilla web tool kit schema example
+35.1k Golang : Upload and download file to/from AWS S3
+13.6k Golang : Get user input until a command or receive a word to stop
+23.6k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+10k CodeIgniter : Load different view for mobile devices
+23.5k Golang : Get ASCII code from a key press(cross-platform) example